#include "PlaylistWidget.h"

#define MAX(a, b) (((a) > (b)) ? (a) : (b))

PlaylistWidget::PlaylistWidget(Playlist * thePlaylist) : QTableWidget(5, 2), playlist(thePlaylist)
{
	QStringList headers;

	headers << "File Name" << "Vote Counter";

	setHorizontalHeaderLabels(headers);	
	setAlternatingRowColors(true);

	verticalHeader()->hide();
	horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);

	playlist->addObserver(this);
}

void PlaylistWidget::notify (Observable * obj, int eventCode)
{
    if (obj == playlist)
		QMetaObject::invokeMethod(this, "playlistUpdated", Qt::QueuedConnection);
}

void PlaylistWidget::playlistUpdated ()
{
	int currentRow = 0;

	std::list<Song>::iterator it;
    std::list<Song> songlist = playlist->copySongList();

	setRowCount(MAX(songlist.size(), 5));

	for (it = songlist.begin(); it != songlist.end(); it++)
	{
		QTableWidgetItem * fileNameItem = new QTableWidgetItem(QString::fromStdString(it->getFilename()));
		QTableWidgetItem * votesItem = new QTableWidgetItem(QString::number(it->getVotes()));

		votesItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

		setItem(currentRow, 0, fileNameItem);
		setItem(currentRow, 1, votesItem);

		currentRow++;
	}
}